import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { HttpService } from '../../shared/service/http.service';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { AlertController } from '@ionic/angular';
import { EventService } from 'src/app/shared/service/event.service';

@Component({
  selector: 'app-certificate-list',
  templateUrl: './certificate-list.component.html',
  styleUrls: ['./certificate-list.component.scss']
})
export class CertificateListComponent implements OnInit {
  @Input() tagData: any;
  dataIndex: any;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  params: any = { content: {} };
  showLoadMore = false;

  constructor(
    private appGlobalService: AppGlobalService,
    private alertController: AlertController,
    private http: HttpService,
    private pageModalService: PageModalService,
    private eventService: EventService,
  ) { }

  ngOnInit() {
    if (this.tagData.data.submit !== undefined) {
      this.params = this.tagData.data.submit;
      this.pageSize = this.tagData.pageSize;
      this.pageTotal = this.tagData.pageTotal;
      this.showLoadMore = !this.tagData.data.moreButton &&
        this.tagData.data.submit &&
        this.pageTotal &&
        (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) &&
        this.tagData.asyncShow !== 'true';
    }

    if (this.eventService.eventEmit.listenerCount('emitcertificateList') > 0) {
      this.eventService.eventEmit.removeListener('emitcertificateList');
    }
    this.eventService.eventEmit.on('emitcertificateList', res => {
      let isChecked;
      try {
        this.tagData.data.data.forEach(element => {
          if (element.checked && (element.checked === true || element.checked === 'true') && element.secondRowLeft.firstText.label) {
            isChecked = true;
            let emitData;
            emitData = {
              id: element.id,
              itemList: [
                { label: element.secondRowLeft.firstText.label, value: element.secondRowLeft.firstText.img },
                element.secondRowLeft.secondText.label ? { label: element.secondRowLeft.secondText.label, value: element.secondRowLeft.secondText.img } : ''
              ]
            }
            console.log(emitData);
            this.eventService.eventEmit.emit('selectCertificates', JSON.stringify(emitData));
            throw Error('return');
          }
        });
      } catch (err) {

      }

      isChecked !== true ? this.appGlobalService.showToast('请选择要提交的证书！', 1500, "top") : '';
    });
  }

  openPage(item) {
    this.pageModalService.openPage(item.link);
  }

  normalBtnClick(buttonItem, index, data?) {
    if (!buttonItem) {
      return;
    }
    this.dataIndex = index;
    this.iconClick(buttonItem, data);
  }

  async iconClick(item, data) {
    const that = this;
    if (item.modelType === "iconLink") {
      that.pageModalService.openPage(item.link);
    } else if (item.modelType === "iconDelete") {
      const alert = await that.alertController.create({
        header: that.tagData.nickName,
        message: item.msg,
        buttons: [
          {
            text: "取消",
            role: "cancel",
            cssClass: "secondary"
          },
          {
            text: '确定',
            handler: () => {
              const params = {
                content: item.button.submit.content,
                id: item.button.submit.id,
                sessionId: localStorage.getItem("sessionId")
              };
              that.http.post("application/submit", params, res => {
                if (res.success) {
                  that.appGlobalService.showToast(res.message, 1500, "middle");
                  if (that.dataIndex >= 0 && that.dataIndex < that.tagData.data.data.length) {
                    that.tagData.data.data.splice(that.dataIndex, 1);
                  }
                } else {
                  that.appGlobalService.showToast(res.message, 1500, "middle");
                }
              });
            }
          }
        ]
      });
      await alert.present();
    }
  }

  checkShow(item, data) {
    data.forEach(e => {
      e.checked = false;
    });
    item.checked = !item.checked;
  }

  loadMoreData(event) {
    this.pageNo = this.pageNo + 1;
    if (this.tagData.data.data.length >= this.tagData.data.pageTotal) {
      event.target.disabled = true;
      // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
      // event.complete();
      return;
    }
    if (this.tagData.data.submit) {
      if (this.tagData.data.submit.content) {
        this.tagData.data.submit.content.pageNo = this.pageNo;
      }
      this.tagData.data.submit.sessionId = localStorage.getItem("sessionId");
    }

    this.http.post(
      "application/submit",
      this.tagData.data.submit,
      res => {
        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          this.tagData.data.submit = res.data.submit;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(item => {
              this.tagData.data.data.push(item);
            });
          } else {
            event.target.disabled = true;
          }
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
        event.target.complete();
      },
      err => {
        this.appGlobalService.showToast(err.message, 2000, "middle");
        event.target.complete();
      }
    );
  }
}
